package cn.edu.sdjzu.knoverse.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.edu.sdjzu.knoverse.model.dto.kg.CaseAuditDTO;
import cn.edu.sdjzu.knoverse.model.dto.kg.CaseDetailDTO;
import cn.edu.sdjzu.knoverse.model.dto.kg.CaseQueryDTO;
import cn.edu.sdjzu.knoverse.model.entity.kg.CaseNode;
import cn.edu.sdjzu.knoverse.model.vo.result.Result;
import cn.edu.sdjzu.knoverse.model.vo.result.ResultCodeEnum;
import cn.edu.sdjzu.knoverse.service.CaseService;
import cn.edu.sdjzu.knoverse.service.RankingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.edu.sdjzu.knoverse.model.enums.CaseType;

/**
 * 案例节点控制器
 */
@RestController
@RequestMapping("/case")
@Tag(name = "案例管理", description = "案例相关接口")
public class CaseController {

    @Autowired
    private CaseService caseService;
    
    @Autowired
    private RankingService rankingService;

    /**
     * 分页查询案例
     *
     * @param queryDTO 查询条件
     * @return 分页案例结果
     */
    @SaCheckPermission("case::list")
    @PostMapping("/list")
    public Result<Page<CaseNode>> listCases(@RequestBody CaseQueryDTO queryDTO) {
        Page<CaseNode> cases = caseService.findCasesByConditions(queryDTO);
        return Result.success(cases);
    }

    /**
     * 获取案例详情
     *
     * @param id 案例ID
     * @return 案例详情
     */
    @SaCheckPermission("case::detail")
    @GetMapping("/{id}")
    public Result<CaseNode> getCaseById(@PathVariable String id) {
        CaseNode caseNode = caseService.findCaseById(id);
        return Result.success(caseNode);
    }
    
    /**
     * 获取完整案例详情（包含案例信息、组件列表、文件和知识点）
     *
     * @param id 案例ID
     * @return 完整案例详情
     */
    @SaCheckPermission("case::complete")
    @GetMapping("/{id}/complete")
    @Operation(summary = "获取完整案例详情", description = "获取案例信息、组件列表、组件文件和知识点")
    public Result<CaseDetailDTO> getCompleteCaseDetail(@PathVariable String id) {
        CaseDetailDTO detailDTO = caseService.getCompleteCaseDetail(id);
        
        // 增加案例点击量计数
        if (detailDTO != null && detailDTO.getCaseInfo() != null) {
            CaseNode caseInfo = detailDTO.getCaseInfo();
            rankingService.incrementCaseClickCount(
                    caseInfo.getNodeId(),
                    caseInfo.getName(),
                    caseInfo.getType()
            );
        }
        
        return Result.success(detailDTO);
    }

    /**
     * 创建案例，默认设置状态为0，草稿
     *
     * @param caseNode 案例实体
     * @return 创建结果
     */
    @SaCheckPermission("case::add")
    @PostMapping
    public Result<CaseNode> createCase(@RequestBody CaseNode caseNode) {
        CaseNode createdCase = caseService.createCase(caseNode);
        return Result.success(createdCase, ResultCodeEnum.ADD_SUCCESS);
    }

    /**
     * 更新案例
     *
     * @param id       案例ID
     * @param caseNode 案例更新内容
     * @return 更新结果
     */
    @SaCheckPermission("case::update")
    @PutMapping("/{id}")
    public Result<CaseNode> updateCase(@PathVariable String id, @RequestBody CaseNode caseNode) {
        CaseNode updatedCase = caseService.updateCase(id, caseNode);
        return Result.success(updatedCase, ResultCodeEnum.UPDATE_SUCCESS);
    }

    /**
     * 删除案例
     *
     * @param id 案例ID
     * @return 删除结果
     */
    @SaCheckPermission("case::delete")
    @DeleteMapping("/{id}")
    public Result<Object> deleteCase(@PathVariable String id) {
        caseService.deleteCase(id);
        return Result.success(null, ResultCodeEnum.DELETE_SUCCESS);
    }

    /**
     * 获取所有案例类型
     *
     * @return 类型列表
     */
    @SaCheckPermission("case::types")
    @GetMapping("/types")
    public Result<List<String>> getAllCaseTypes() {
        List<String> types = Arrays.stream(CaseType.values())
                .map(CaseType::getDescription)
                .collect(Collectors.toList());
        return Result.success(types);
    }

    /**
     * 提交案例，将案例状态设置为1，等待审核
     */
    @SaCheckPermission("case::submit")
    @PostMapping("/submit/{id}")
    public Result<Object> submitCase(@PathVariable String id) {
        caseService.submitCase(id);
        return Result.success(null, ResultCodeEnum.SUCCESS);
    }


    /**
     * 发布案例，将案例状态设置为2
     *
     * @param id 案例ID
     * @return 发布结果
     */
    @SaCheckPermission("case::publish")
    @PostMapping("/publish/{id}")
    public Result<Object> publishCase(@PathVariable String id) {
        caseService.publishCase(id);
        return Result.success(null, ResultCodeEnum.SUCCESS);
    }

    /**
     * 下架案例，将案例状态设置为4
     *
     * @param id 案例ID
     * @return 下架结果
     */
    @SaCheckPermission("case::unpublish")
    @PostMapping("/unpublish/{id}")
    public Result<Object> unpublishCase(@PathVariable String id) {
        caseService.unpublishCase(id);
        return Result.success(null, ResultCodeEnum.SUCCESS);
    }

    /**
     * 审核案例，审核案例状态为1的案例，决定是否发布，还是审核失败，失败设置为3，发布设置为2
     *
     * @param id 案例ID，审核结果，审核信息
     * @return 审核结果
     */
    @SaCheckPermission("case::audit")
    @PostMapping("/audit/{id}")
    public Result<Object> auditCase(@PathVariable String id, @RequestBody CaseAuditDTO auditDTO) {
        caseService.auditCase(id, auditDTO);
        return Result.success(null, ResultCodeEnum.SUCCESS);
    }
} 